<template>
  <div class="enter-out-analysis">
    <el-card class="header-card">
      <div class="header-content">
        <h2>出入库实时分析</h2>
        <div class="connection-status">
          <el-tag :type="connectionStatus ? 'success' : 'danger'" size="large">
            {{ connectionStatus ? '已连接' : '未连接' }}
          </el-tag>
          <el-button 
            v-if="!connectionStatus" 
            @click="connectSignalR" 
            type="primary" 
            size="small"
          >
            重新连接
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon in-icon">
            <el-icon><ArrowUp /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ analysisData.totalIn }}</div>
            <div class="stat-label">总入库量</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon out-icon">
            <el-icon><ArrowDown /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ analysisData.totalOut }}</div>
            <div class="stat-label">总出库量</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon net-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value" :class="{ 'positive': analysisData.netChange > 0, 'negative': analysisData.netChange < 0 }">
              {{ analysisData.netChange > 0 ? '+' : '' }}{{ analysisData.netChange }}
            </div>
            <div class="stat-label">净变化</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>每日出入库趋势</span>
              </div>
            </template>
            <div class="chart-container">
              <v-chart :option="dailyChartOption" style="height: 300px;" />
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>仓库统计</span>
              </div>
            </template>
            <div class="chart-container">
              <v-chart :option="warehouseChartOption" style="height: 300px;" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 实时数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>实时出入库记录</span>
          <el-button @click="refreshData" type="primary" size="small">
            刷新数据
          </el-button>
          <el-button @click="testData" type="warning" size="small">
            测试数据
          </el-button>
          <el-button @click="testSignalR" type="info" size="small">
            测试SignalR
          </el-button>
        </div>
      </template>
      
      <el-table :data="enterOutData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="单号" />
        <el-table-column prop="incomingQuantity" label="数量" width="100" />
        <el-table-column prop="state" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.state === 2 ? 'success' : 'danger'">
              {{ scope.row.state === 2 ? '入库' : '出库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="depotName" label="仓库" width="120" />
        <el-table-column prop="stName" label="类型名称" width="120" />
        <el-table-column prop="dateTime" label="日期时间" width="180" />
        <el-table-column prop="incomingMoney" label="金额" width="100" />
      </el-table>
    </el-card>

    <!-- 热门产品统计 -->
    <el-card class="top-products-card">
      <template #header>
        <div class="card-header">
          <span>热门产品统计</span>
        </div>
      </template>
      
      <div class="top-products-list">
        <div 
          v-for="(product, index) in analysisData.topProducts" 
          :key="index"
          class="product-item"
        >
          <div class="product-rank">{{ index + 1 }}</div>
          <div class="product-info">
            <div class="product-name">{{ product.productName }}</div>
            <div class="product-quantity">
              数量: {{ product.totalQuantity }}
              <el-tag :type="product.type === '入库' ? 'success' : 'danger'" size="small">
                {{ product.type }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowUp, ArrowDown, TrendCharts } from '@element-plus/icons-vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { signalRService, type EnterOutDTO, type AnalysisData } from './eo'
import http from '@/http/axiosHelper'
// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 响应式数据
const connectionStatus = ref(false)
const loading = ref(false)
const enterOutData = ref<EnterOutDTO[]>([])
const analysisData = reactive<AnalysisData>({
  totalIn: 0,
  totalOut: 0,
  netChange: 0,
  dailyStats: [],
  topProducts: [],
  warehouseStats: []
})

// 计算图表选项
const dailyChartOption = computed(() => ({
  title: {
    text: '每日出入库趋势',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['入库', '出库', '净变化'],
    top: 30
  },
  xAxis: {
    type: 'category',
    data: analysisData.dailyStats.map(item => item.date)
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '入库',
      type: 'line',
      data: analysisData.dailyStats.map(item => item.inCount),
      itemStyle: { color: '#67C23A' }
    },
    {
      name: '出库',
      type: 'line',
      data: analysisData.dailyStats.map(item => item.outCount),
      itemStyle: { color: '#F56C6C' }
    },
    {
      name: '净变化',
      type: 'line',
      data: analysisData.dailyStats.map(item => item.netChange),
      itemStyle: { color: '#409EFF' }
    }
  ]
}))

const warehouseChartOption = computed(() => ({
  title: {
    text: '仓库出入库统计',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '仓库统计',
      type: 'pie',
      radius: '50%',
      data: analysisData.warehouseStats.map(item => ({
        name: item.warehouse,
        value: item.inCount + item.outCount
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}))

// 连接SignalR
const connectSignalR = async () => {
  try {
    loading.value = true
    console.log('开始连接SignalR...')
    
    await signalRService.createConnection()
    connectionStatus.value = signalRService.getConnectionStatus()
    
    console.log('SignalR连接状态:', connectionStatus.value)
    
    if (!connectionStatus.value) {
      throw new Error('SignalR连接失败')
    }
    
    // 监听出入库数据
    signalRService.onReceiveEnterOutData((data: any) => {
      console.log('=== 收到SignalR数据 ===')
      console.log('原始数据类型:', typeof data)
      console.log('是否为数组:', Array.isArray(data))
      console.log('原始数据:', JSON.stringify(data, null, 2))
      
      let processedData: EnterOutDTO[] = []
      if (Array.isArray(data)) {
        console.log('处理数组数据，长度:', data.length)
        processedData = data.map((item, index) => {
          const processed = {
            id: item.Id || item.id,
            stockId: item.StockId || item.stockId,
            code: item.Code || item.code,
            dateTime: item.DateTime || item.dateTime,
            businessType: item.BusinessType || item.businessType,
            stId: item.STId || item.stId,
            stName: item.STName || item.stName,
            depotId: item.DepotId || item.depotId,
            depotName: item.DepotName || item.depotName,
            incomingQuantity: item.IncomingQuantity || item.incomingQuantity,
            incomingMoney: item.IncomingMoney || item.incomingMoney,
            state: item.State || item.state,
          }
          console.log(`处理第${index + 1}条数据:`, processed)
          return processed
        })
      } else if (data && typeof data === 'object') {
        console.log('处理单个对象数据')
        processedData = [{
          id: data.Id || data.id,
          stockId: data.StockId || data.stockId,
          code: data.Code || data.code,
          dateTime: data.DateTime || data.dateTime,
          businessType: data.BusinessType || data.businessType,
          stId: data.STId || data.stId,
          stName: data.STName || data.stName,
          depotId: data.DepotId || data.depotId,
          depotName: data.DepotName || data.depotName,
          incomingQuantity: data.IncomingQuantity || data.incomingQuantity,
          incomingMoney: data.IncomingMoney || data.incomingMoney,
          state: data.State || data.state,
        }]
      }

      console.log('=== 最终处理后的数据 ===')
      console.log('处理后的数据:', processedData)
      console.log('数据长度:', processedData.length)
      
      enterOutData.value = processedData
      updateAnalysisData(processedData)
      ElMessage.success(`收到 ${processedData.length} 条真实数据`)
    })
    
    // 监听连接状态变化
    const checkConnection = () => {
      const currentStatus = signalRService.getConnectionStatus()
      if (currentStatus !== connectionStatus.value) {
        console.log('连接状态变化:', connectionStatus.value, '->', currentStatus)
        connectionStatus.value = currentStatus
        
        // 如果连接断开，尝试重新连接
        if (!currentStatus) {
          console.log('连接断开，尝试重新连接...')
          setTimeout(async () => {
            try {
              await signalRService.createConnection()
              connectionStatus.value = signalRService.getConnectionStatus()
              console.log('重新连接成功')
            } catch (error) {
              console.error('重新连接失败:', error)
            }
          }, 2000)
        }
      }
    }
    
    // 定期检查连接状态
    const connectionCheckInterval = setInterval(checkConnection, 3000)
    
    // 在组件卸载时清理定时器
    onUnmounted(() => {
      clearInterval(connectionCheckInterval)
    })
    
    ElMessage.success('SignalR连接成功')
  } catch (error) {
    console.error('连接失败:', error)
    ElMessage.error('SignalR连接失败')
  } finally {
    loading.value = false
  }
}

// 更新分析数据
const updateAnalysisData = (data: EnterOutDTO[]) => {
  console.log('开始更新分析数据，数据长度:', data.length)
  
  // 计算总入库和出库量
  const inData = data.filter(item => item.state === 2) // 2表示入库
  const outData = data.filter(item => item.state === 1) // 1表示出库
  
  console.log('入库数据数量:', inData.length)
  console.log('出库数据数量:', outData.length)
  
  analysisData.totalIn = inData.reduce((sum, item) => sum + item.incomingQuantity, 0)
  analysisData.totalOut = outData.reduce((sum, item) => sum + item.incomingQuantity, 0)
  analysisData.netChange = analysisData.totalIn - analysisData.totalOut
  
  // 按日期分组统计
  const dailyMap = new Map()
  data.forEach(item => {
    const date = item.dateTime.split(' ')[0] // 只取日期部分
    if (!dailyMap.has(date)) {
      dailyMap.set(date, { inCount: 0, outCount: 0, netChange: 0 })
    }
    const stats = dailyMap.get(date)
    if (item.state === 2) { // 入库
      stats.inCount += item.incomingQuantity
    } else if (item.state === 1) { // 出库
      stats.outCount += item.incomingQuantity
    }
    stats.netChange = stats.inCount - stats.outCount
  })
  
  analysisData.dailyStats = Array.from(dailyMap.entries()).map(([date, stats]) => ({
    date,
    inCount: stats.inCount,
    outCount: stats.outCount,
    netChange: stats.netChange
  }))
  
  // 按仓库分组统计
  const warehouseMap = new Map()
  data.forEach(item => {
    if (!warehouseMap.has(item.depotName)) {
      warehouseMap.set(item.depotName, { inCount: 0, outCount: 0 })
    }
    const stats = warehouseMap.get(item.depotName)
    if (item.state === 2) { // 入库
      stats.inCount += item.incomingQuantity
    } else if (item.state === 1) { // 出库
      stats.outCount += item.incomingQuantity
    }
  })
  
  analysisData.warehouseStats = Array.from(warehouseMap.entries()).map(([warehouse, stats]) => ({
    warehouse,
    inCount: stats.inCount,
    outCount: stats.outCount
  }))
  
  // 热门产品统计
  const productMap = new Map()
  data.forEach(item => {
    const key = `${item.code}_${item.state}`
    if (!productMap.has(key)) {
      productMap.set(key, { 
        productName: item.code, 
        totalQuantity: 0, 
        type: item.state === 2 ? '入库' : '出库' 
      })
    }
    productMap.get(key).totalQuantity += item.incomingQuantity
  })
  
  analysisData.topProducts = Array.from(productMap.values())
    .sort((a, b) => b.totalQuantity - a.totalQuantity)
    .slice(0, 10)
}

// 刷新数据
const refreshData = () => {
  if (enterOutData.value.length > 0) {
    updateAnalysisData(enterOutData.value)
    ElMessage.success('数据已刷新')
  }
}

// 测试数据
const testData = () => {
  ElMessage.warning('已移除虚拟数据功能，请使用"测试SignalR"按钮获取真实数据')
}

// 测试SignalR连接
const testSignalR = async () => {
  console.log('测试SignalR连接状态:', connectionStatus.value)
  console.log('当前数据长度:', enterOutData.value.length)
  console.log('分析数据:', analysisData)
  
  // 主动请求后端推送数据
  try {
    const response = await fetch('http://112.126.93.146:8000/scmreadconsul/api/SignalR/Push')
    if (response.ok) {
      const result = await response.text()
      console.log('后端推送响应:', result)
      ElMessage.success('已请求后端推送数据，请查看是否收到')
    } else {
      console.error('请求后端推送失败:', response.status)
      ElMessage.error('请求后端推送失败')
    }
  } catch (error) {
    console.error('请求后端推送出错:', error)
    ElMessage.error('请求后端推送出错')
  }
}

// 生命周期
onMounted(async () => {
  await connectSignalR()
  
  // 页面加载后主动请求一次后端数据
  setTimeout(async () => {
    try {
      const response = await fetch('http://112.126.93.146:8000/scmreadconsul/push')
      if (response.ok) {
        const result = await response.text()
        console.log('页面初始化时请求后端推送响应:', result)
      } else {
        console.error('页面初始化时请求后端推送失败:', response.status)
      }
    } catch (error) {
      console.error('页面初始化时请求后端推送出错:', error)
    }
  }, 2000) // 延迟2秒，确保SignalR连接已建立
})

onUnmounted(async () => {
  await signalRService.stopConnection()
})
</script>

<style scoped>
.enter-out-analysis {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.in-icon {
  background: linear-gradient(135deg, #67C23A, #85CE61);
}

.out-icon {
  background: linear-gradient(135deg, #F56C6C, #F78989);
}

.net-icon {
  background: linear-gradient(135deg, #409EFF, #66B1FF);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-value.positive {
  color: #67C23A;
}

.stat-value.negative {
  color: #F56C6C;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-container {
  height: 300px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.top-products-card {
  margin-bottom: 20px;
}

.top-products-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 15px;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.product-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.product-rank {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409EFF, #66B1FF);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.product-quantity {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
  font-size: 14px;
}
</style>
